package com.unionpay.upyzt.util;

import java.security.SecureRandom;
import java.util.regex.Pattern;

import static java.util.Objects.requireNonNull;

public class StringUtils {

    /**
     * 空字符
     */
    public static final String EMPTY = "";

    /**
     * 换行符
     */
    public static final String CRLF = "\r\n";

    /**
     * 下划线字符
     */
    public static final char UNDERLINE = '_';

    private static final Pattern whitespacePattern = Pattern.compile("\\s");

    /**
     * 是否包含空格
     *
     * @param str 字符串
     * @return 包含 {@code true}; 不包含 {@code false}.
     */
    public static boolean containsWhitespace(String str) {
        requireNonNull(str);
        return whitespacePattern.matcher(str).find();
    }

    /**
     * 是否为空
     *
     * @param cs 字符串
     * @return 空 {@code true}; 非空 {@code false}.
     */
    public static boolean isBlank(final CharSequence cs) {
        if (cs == null) {
            return true;
        }
        int l = cs.length();
        if (l > 0) {
            for (int i = 0; i < l; i++) {
                if (!Character.isWhitespace(cs.charAt(i))) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 字符串驼峰转下划线格式
     *
     * @param param 需要转换的字符串
     * @return 转换好的字符串
     */
    public static String camelToUnderline(String param) {
        if (isBlank(param)) {
            return EMPTY;
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (Character.isUpperCase(c) && i > 0) {
                sb.append(UNDERLINE);
            }
            sb.append(Character.toLowerCase(c));
        }
        return sb.toString();
    }

    /**
     * 生成随机数字字母字符串
     *
     * @param length 字符串长度
     * @return 字符串
     */
    public static String randomAlphanumeric(int length) {
        SecureRandom random = new SecureRandom();
        return random.ints(48, 123)
                .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97))
                .limit(length)
                .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
                .toString();
    }


    /**
     * 生成随机数字字符串
     *
     * @param length 字符串长度
     * @return 字符串
     */
    public static String randomNumeric(int length) {
        SecureRandom random = new SecureRandom();
        return random.ints(48, 57)
                .limit(length)
                .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
                .toString();
    }

    /**
     * 获取当前时间戳字符串
     *
     * @return 当前时间戳字符串
     */
    public static String currentTimeStamp() {
        int requestTime = (int) (System.currentTimeMillis() / 1000);
        return Integer.toString(requestTime);
    }
}
